package cn.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;

import dao.ExamDao;
import entity.Exam;

public class ExamJsonServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public ExamJsonServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	private ExamDao dao = new ExamDao();

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int pageNo = 1;

		try {
			pageNo = Integer.parseInt(request.getParameter("p"));
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			// e.printStackTrace();
		}

		Map<String, Object> m = new HashMap<>();
		int total = dao.getTotalPage();

		List<Exam> list = dao.paging(pageNo);
		m.put("totalPages", total);
		m.put("datas", list);

		// String str = JSON.toJSONString(list,
		// SerializerFeature.UseISO8601DateFormat);// ,SerializerFeature.
		// String str = JSON.toJSONStringWithDateFormat(list, "yyyy/MM/dd");
		String str = JSON.toJSONStringWithDateFormat(m, "yyyy/MM/dd");
		response.setContentType("application/json;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.print(str);
		out.flush();
		// out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
